package com.yizhiliulianta.wx.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration // 表明这是一个配置类
public class RedisConfig {

    /**
     * 配置RedisTemplate以防止数据序列化和反序列化时出现乱码
     * @param redisConnectionFactory Redis连接工厂
     * @return 配置好的RedisTemplate
     */
    @Bean // 表示这是一个Spring Bean，会被Spring管理
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 创建字符串序列化器
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();

        // 设置Redis连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置键的序列化器为字符串序列化器
        redisTemplate.setKeySerializer(redisSerializer);
        // 设置哈希键的序列化器为字符串序列化器
        redisTemplate.setHashKeySerializer(redisSerializer);

        // 设置值的序列化器为自定义的Jackson2JsonRedisSerializer
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
        // 设置哈希值的序列化器为自定义的Jackson2JsonRedisSerializer
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());

        return redisTemplate; // 返回配置好的RedisTemplate
    }

    /**
     * 创建并配置Jackson2JsonRedisSerializer，用于将Java对象序列化为JSON格式
     * @return 配置好的Jackson2JsonRedisSerializer
     */
    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        // 创建Jackson2JsonRedisSerializer实例
        Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        // 设置ObjectMapper的可见性，使所有属性都可见（包括私有属性）
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 配置ObjectMapper，在反序列化时忽略未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        // 启用默认类型信息，以便处理多态类型
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        // 将配置好的ObjectMapper设置到Jackson2JsonRedisSerializer
        jsonRedisSerializer.setObjectMapper(objectMapper);

        return jsonRedisSerializer; // 返回配置好的Jackson2JsonRedisSerializer
    }

}
